<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';

import { useAccess } from '@vben/access';
import { useVbenModal } from '@vben/common-ui';
import { useUserStore } from '@vben/stores';
import { cloneDeep } from '@vben/utils';

import { Modal } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { paymentAdjustmentApprove } from '#/api/hm/paymentAdjustment';
import {
  processingAgent,
  todoItemsAdd,
  todoItemsInfo,
  todoItemsUpdate,
} from '#/api/hm/todoItems';
import { deptList } from '#/api/system/dept';

import { modalSchema } from './data';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const isEdit = ref(false);
const title = computed(() => {
  return isEdit.value ? '编辑' : (isUpdate.value ? '办理' : '回访');
});
const userStore = useUserStore();

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-1',
    // 默认label宽度 px
    labelWidth: 70,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: modalSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel: handleCancel,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id } = modalApi.getData() as { id?: number | string };
    const { outRecordId, edit } = modalApi.getData() as {
      edit: false;
      outRecordId?: number | string;
    };
    isUpdate.value = !!id;
    isEdit.value = edit;

    if (isUpdate.value && id) {
      const record = await todoItemsInfo(id);
      if (outRecordId) {
        // const outRecordInfo = await issueReceiptRecordsInfo(outRecordId);
        // record.
      }
      record.isEdit = isEdit.value;
      await formApi.setValues(record);
    }
    modalApi.modalLoading(false);
    // 根据出库单查询出库详情数据
  },
});

async function handleConfirm() {
  try {
    modalApi.modalLoading(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    Modal.confirm({
      title: '提示',
      okType: 'danger',
      content: `确定提交吗？`,
      onOk: async () => {
        // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
        const data = cloneDeep(await formApi.getValues());

        // 特殊处理：回款调整待办
        if (isUpdate.value && data.todoType === '9') {
          // 从 remark 中提取 adjustmentId
          const adjustmentId = data.remark?.match(/adjustmentId:(\d+)/)?.[1];

          if (adjustmentId) {
            try {
              // 调用专用的批准接口
              await paymentAdjustmentApprove(
                adjustmentId,
                data.todoResult || '',
              );
              // 更新待办状态为已完成
              data.status = 1;
              // await processingAgent(data);
              emit('reload');
              await handleCancel();
              return;
            } catch (error) {
              console.error('回款调整批准失败:', error);
              throw error;
            }
          }
        }

        // 原有的处理逻辑
        if (isUpdate.value) {
          data.status = 1;
          data.isAgain = false;
        } else if (data.todoType === '0') {
          data.status = 1;
        } else {
          data.todoStockDept = userStore.userInfo?.deptId;
        }
        await (isEdit.value
          ? todoItemsUpdate(data) // 编辑更新
          : (isUpdate.value
            ? processingAgent(data) // 办理
            : todoItemsAdd(data))); // 新增回访
        emit('reload');
        await handleCancel();
      },
    });
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.modalLoading(false);
  }
}

async function handleCancel() {
  modalApi.close();
  await formApi.resetForm();
}

// 操作产品Schema 更新
// onMounted(async () => {
//   const ret = await productList({
//     pageNum: 1,
//     pageSize: 999,
//     status: '0',
//     productType: 'CP',
//   });
//   const dataSourceOptions = [];
//   const transOptions = ret.rows.map((item) => ({
//     label: item.productName,
//     value: item.productId.toString(),
//   }));
//   dataSourceOptions.push(...transOptions);
//   formApi.updateSchema([
//     {
//       fieldName: 'todoStockGoodsId',
//       componentProps: {
//         options: dataSourceOptions,
//         allowClear: true,
//         showSearch: true,
//         optionFilterProp: 'label',
//       },
//     },
//   ]);
// });

const { hasAccessByRoles } = useAccess();
const isAdmin = computed(() => {
  return hasAccessByRoles(['admin', 'superadmin', 'ceo']);
});
// 获取服务店铺列表
onMounted(async () => {
  const requestParams = { ancestors: '101', deptCategory: 'DP' };
  if (isAdmin.value) {
    requestParams.deptCategory = '';
  }
  const deptTree = await deptList(requestParams);
  const deptOptions = [];
  const deptTransOptions = deptTree.map((item) => ({
    label: item.deptName,
    value: item.deptId,
  }));
  deptOptions.push(...deptTransOptions);
  formApi.updateSchema([
    {
      fieldName: 'todoStockDept',
      componentProps: {
        options: deptOptions,
        showSearch: true,
        optionFilterProp: 'label',
      },
    },
  ]);
});
// 回访客户Schema 更新
</script>

<template>
  <BasicModal :close-on-click-modal="false" :title="title" class="w-[1100px]">
    <BasicForm />
  </BasicModal>
</template>
